package com.mini6410.EEPROM;

import android.os.Handler;
import android.util.Log;

import com.friendlyarm.AndroidSDK.HardwareControler;

public class WriteEEPROM{
	private static final String TAG = "WriteEEPROM";

	private static final int MAX_LENGTH = 256; //EEPROM最多可存储256个字节数据

	Handler mHandler = null;

	byte[] mData = null;

	private WriteEEPROMThread mWriteEEPROMThread = null;

	public WriteEEPROM(Handler mHandler){
		this.mHandler = mHandler;
	}

	public void WriteData(byte[] data){
		mData = data;

		safeStop();

		mWriteEEPROMThread = new WriteEEPROMThread();
		mWriteEEPROMThread.start();
	}

	public void safeStop(){
		if(mWriteEEPROMThread != null && mWriteEEPROMThread.isAlive()){
			mWriteEEPROMThread.interrupt();
			mWriteEEPROMThread.stop = true;
			try {
				mWriteEEPROMThread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		mWriteEEPROMThread = null;
	}

	public void sendMessage(int what ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what));
		}	
	}

	public void sendMessage(int what, Object obj ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what, obj));
		}
	}

	public void sendMessage(int what, int arg1,int arg2,Object obj ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj));
		}
	}


	public void sendMessage(int what, int arg1,int arg2 ){
		if(mHandler != null){
			mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2));
		}
	}

	private class WriteEEPROMThread extends Thread{
		volatile boolean stop = false;

		int fd = 0; 
		int length = 0;
		int pos = 0;

		@Override
		public void run() {

			if(mData == null){
				Log.e(TAG, "There is No Data!");

				stop = true;
			}

			fd = HardwareControler.openI2CDevice();

			if(fd == -1)
			{
				Log.e(TAG, "Failed to open the I2CDevice !");

				stop = true;
			}


			length = mData.length;

			if (length > MAX_LENGTH) {
				length = MAX_LENGTH;
			}

			for(int i = 0 ; i < MAX_LENGTH; i++){
				HardwareControler.writeByteDataToI2C(fd, i, (byte)'\0');
			}

			while(!stop){

				if (pos >= length) {
					break;
				}

				HardwareControler.writeByteDataToI2C(fd, pos, mData[pos]);
				
				sendMessage(EEPROMActivity.MSG_UPDATE_UI, pos,length);

				Log.i(TAG, "writeByteDataToI2C pos: "+ pos);

				pos++;

//				try {
//					Thread.sleep(10);
//				} catch ( InterruptedException e ) {
//					e.printStackTrace();
//				}

			}

			if(fd != -1)
			{
				HardwareControler.close(fd);
			}

		}
	}
}
